package com.ruoyi.task.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.task.domain.StreamPictureParams;
import com.ruoyi.task.domain.StreamPictureResult;
import com.ruoyi.task.domain.TaskDetailResult;
import com.ruoyi.task.domain.TaskDetailResultParams;
import com.ruoyi.task.mapper.HyMapper;
import com.ruoyi.task.service.IHaoYunService;
import com.ruoyi.task.service.ITaskDetailResultService;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;

@Service
public class HaoYunServiceImpl implements IHaoYunService {


    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 实时码流方式获取接口
     */
    @Value("${realStreamPictureUrl:http://10.223.7.72:12067/video/getRealStreamPictureSync}")
    private String realStreamPictureUrl;

    /**
     * 从影像中获取指定抓拍 接口
     */
    @Value("${historicalStreamPictureUrl:http://10.223.7.72:12067/video/getHistoricalStreamPictureSync}")
    private String historicalStreamPictureUrl;

    /**
     * 浩云获取token服务接口
     */
    @Value("${hyOauthTokenUrl:http://10.223.7.93:9000/oauth/token}")
    private String hyOauthTokenUrl;

    private String user;

    private String pwd;


    @Autowired
    private ITaskDetailResultService taskDetailResultService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private HyMapper hyMapper;


    @Override
    public StreamPictureResult realStreamPictureSync(StreamPictureParams streamPictureParams) {
        try {
            String params = JSON.toJSONString(streamPictureParams);
            logger.info("realStreamPictureSync params = {}", params);
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", MediaType.APPLICATION_JSON_VALUE);

            String rspStr = HttpUtils.sendPost(realStreamPictureUrl, params,
                    headers, 60000);
//            logger.info("realStreamPictureSync result = {}", rspStr);
            if (StringUtils.isNotBlank(rspStr)) {
                String data = JSON.parseObject(rspStr).getString("data");
                StreamPictureResult result = JSON.parseObject(data, StreamPictureResult.class);
                if (StringUtils.equals("0", result.getResponseCode())) {
                    logger.info("realStreamPictureSync haoyun success");
                    return result;
                } else {
                    logger.error("realStreamPictureSync serialNo = {}, error msg = {}",
                            streamPictureParams.getSerialNo(), result.getResponseMsg());
                    throw new BaseException(result.getResponseMsg());
                }
            }
        } catch (BaseException be) {
            throw be;
        } catch (Exception e) {
            logger.error("realStreamPictureSync error :", e);
        }
        throw new BaseException("获取图片失败");
    }

    @Override
    public StreamPictureResult historicalStreamPictureSync(
            StreamPictureParams streamPictureParams) {
        try {
            String params = JSON.toJSONString(streamPictureParams);
            logger.info("historicalStreamPictureSync params = {}", params);
            Map<String, String> headers = new HashMap();
            headers.put("Content-Type", MediaType.APPLICATION_JSON_VALUE);

            String rspStr = HttpUtils.sendPost(historicalStreamPictureUrl, params,
                    headers, 30000);
//            logger.info("historicalStreamPictureSync result = {}", rspStr);
            if (StringUtils.isNotBlank(rspStr)) {
                String data = JSON.parseObject(rspStr).getString("data");
                StreamPictureResult result = JSON.parseObject(data, StreamPictureResult.class);
                if (StringUtils.equals("0", result.getResponseCode())) {
                    logger.info("historicalStreamPictureSync haoyun success");
                    return result;
                } else {
                    logger.error("streamPictureParams serialNo = {}, error msg = {}, code = {}",
                            streamPictureParams.getSerialNo(), result.getResponseMsg(), result.getResponseCode());
                    throw new BaseException("streamPicture", result.getResponseCode(), null,
                            result.getResponseMsg());
                }
            }
        } catch (BaseException be) {
            throw be;
        } catch (Exception e) {
            logger.error("historicalStreamPictureSync error :", e);
        }
        return null;
    }


    @Override
    public String oauthToken() {
        try {
            JSONObject json = new JSONObject();
            json.put("client_id", user);
            json.put("client_secret", pwd);
            json.put("grant_type", "client_credentials");

            String params = json.toJSONString();
            logger.info("oauthToken params = {}", params);
            String rspStr = HttpUtils.sendPost(hyOauthTokenUrl, params,
                    MediaType.APPLICATION_JSON_VALUE);
            logger.info("oauthToken result = {}", rspStr);
            if (StringUtils.isNotBlank(rspStr)) {
                JSONObject data = JSON.parseObject(rspStr).getJSONObject("data");
                if (StringUtils.equals("0", data.getString("responseCode"))) {
                    // TODO 设置key值
                    return data.getString("token");
                } else {
                    throw new BaseException(data.getString("responseMsg"));
                }
            }

        } catch (Exception e) {
            logger.error("oauthToken error :", e);
        }
        throw new BaseException("获取token失败");
    }


    @Override
    public boolean syncTaskDetailResult(String syncType) {
        try {
            TaskDetailResultParams params = new TaskDetailResultParams();
            String scenariosType = configService.selectConfigByKey("sys.task.abScenariosType");

            // 设置安保场景数据
            if (StringUtils.isNotBlank(scenariosType)) {
                params.setScenariosType(scenariosType);
            }
            if (!StringUtils.equals("all", syncType)) {
                params.setStartTime(DateUtils.addMinutesAgo(15));
            }

            // 查询本系统数据库
            List<TaskDetailResult> results = taskDetailResultService.selectTaskDetailResultList(
                    params);

            // 插入浩云数据库
            if (results != null && !results.isEmpty()) {
                int count = 0;
                for (TaskDetailResult taskDetailResult : results) {
                    count += saveTaskDetailResult(taskDetailResult);
                }
                logger.info("syncTaskDetailResult haoyun success count = {}", count);
            }
            return true;
        } catch (Exception e) {
            logger.error("syncTaskDetailResult error ", e);
        }
        return false;
    }

    @Override
    public int deleteTaskDetailResult(List<String> ids) {
        try {
            return hyMapper.deleteTaskDetailResultById(ids);
        } catch (Exception e) {
            logger.error("deleteTaskDetailResult error :", e);
        }
        return 0;
    }

    @Override
    public int saveTaskDetailResult(TaskDetailResult taskDetailResult) {
        return hyMapper.saveTaskDetailResult(taskDetailResult);
    }
}
